<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 消息警告区 -->
      <el-alert title="添加商品信息" type="info" center show-icon> </el-alert>
      <!-- 步骤条区域 -->
      <el-steps :active="activeIndex - 0" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab区域 -->
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addFormRef"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="Number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="Number"></el-input>
            </el-form-item>
            <!-- 商品分类 -->
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="catePeops"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTabData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="e"
                  v-for="(e, i) in item.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTabData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 图片上传 -->
          <el-tab-pane label="商品图片" name="3">
            <!-- action 图片要上传到的后台API地址 -->
            <!-- on-preview  图片预览事件 -->
            <!-- on-remove 移除图片事件 -->
            <!-- on-success 图片上传成功时的钩子函数 -->
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture"
              :headers="headersObj"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.goods_introduce"> </quill-editor>
            <el-button type="primary" class="btnAdd" @click="add"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览对话框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewdialogVisible"
      width="50%"
    >
      <img :src="previewPath" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import { catData ,tabStateData ,addShop} from '@/request/goodsAPI'
import _ from "lodash";
export default {
  data() {
    return {
      activeIndex: "0",
      //   添加商品的数据对象
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [], // 商品的分类数组
        pics: [], //  图片的数组
        goods_introduce: "", //  富文本
        attrs:[]
      },
      //   表单验证规则
      addRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },
      //   分类数据
      cateList: [],
      // 联级选择器 配置项
      catePeops: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      // 动态参数列表数据
      manyTabData: [],
      // 静态属性数据列表
      onlyTabData: [],
      uploadURL: "https://www.liulongbin.top:8888/api/private/v1/upload",
      // 上传图片的请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      //   图片路径
      previewPath: "",
      //   图片预览对话框开关
      previewdialogVisible: false,
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      let { data: res } = await catData("categories");
      if (res.meta.status !== 200) return this.$message.error("获取数据失败！");
      this.cateList = res.data;
      //   console.log(res);
    },
    // 级联选择器选中变化触发函数
    handleChange() {
      // console.log(this.catePeops.goods_cat);
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
      }
    },
    // 切换标签之前的钩子 第一个值是进入的标签  第二个是离开的标签
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName == "0" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请选择商品分类");
        return false;
      }
      // console.log(activeName,oldActiveName);
    },
    async tabClicked() {
      if (this.activeIndex === "1") {

        let { data: res } = await tabStateData(this.cateId,"many");

        console.log(res.data);
        if (res.meta.status !== 200)
          return this.$message.error("获取动态参数列表数据失败");
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length == 0 ? [] : item.attr_vals.split(" ");
        });
        this.manyTabData = res.data;
      } else if (this.activeIndex === "2") {

        let { data: res } = await tabStateData(this.cateId,"only");

        if (res.meta.status !== 200)
          return this.$message.error("获取静态属性列表数据失败");
        this.onlyTabData = res.data;
      }
    },
    // 预览效果
    handlePreview(file) {
      console.log(file);
      this.previewPath = file.response.data.url;
      this.previewdialogVisible = true;
    },
    // 移除图片的操作
    handleRemove(file) {
      let filePath = file.response.data.tmp_path;
      let idx = this.addForm.pics.findIndex((item) => item.pic == filePath);
      this.addForm.pics.splice(idx, 1);
    },
    // 图片上传成功后的函数
    handleSuccess(response) {
      // console.log(response);
      // 1. 拼接到一个图片信息对象
      const picInfo = { pic: response.data.tmp_path };
      // 2. 将图片信息Push到pics数组中
      this.addForm.pics.push(picInfo);
      console.log(this.addForm.pics);
    },
    // 添加商品
    add() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请填写必要的表单项");
        // 深拷贝 转换成字符串
        const form = _.cloneDeep(this.addForm);
        form.goods_cat = form.goods_cat.join(",");
        // 处理动态参数
        this.manyTabData.forEach(item =>{
            const newInfo = {
                attr_id:item.attr_id,
                attr_vals:item.attr_vals.join(' ')
            }
            this.addForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyTabData.forEach(item =>{
            const newInfo = {
                attr_id:item.attr_id,
                attr_vals:item.attr_vals
            }
            this.addForm.attrs.push(newInfo)
        })
        form.attrs = this.addForm.attrs
        // 发起请求添加商品  商品名称必须时唯一的
        let {data:res} = await addShop(form)
        if(res.meta.status !==201) return this.$message.error('添加商品失败')
        this.$message.success('添加商品成功！')
        this.$router.push('/goods')
      });
      console.log(this.addForm);
    },
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      } else {
        return null;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
}
.el-steps {
  margin: 15px 0px;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
img {
  width: 100%;
}
.btnAdd {
  margin-top: 15px;
}
</style>